package org.flint92.springboot.websocket.endpoint;

import com.google.common.collect.Maps;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;

/**
 * @author flint92
 */
@ServerEndpoint("/chat-room/{username}")
public class ChatRoomServerEndpoint {

    private static final Map<String, Session> livingSession = Maps.newConcurrentMap();

    @OnOpen
    public void openSession(@PathParam("username") String username, Session session) {
        livingSession.put(session.getId(), session);

        sendTextToAll("welcome " + username + " into the room.");
    }

    @OnMessage
    public void onMessage(@PathParam("username") String username,
                          Session session,
                          String message) {
//        sendText(session, "[user: " + username +"]: " + message);
        sendTextToAll("[user: " + username +"]: " + message);
    }

    @OnClose
    public void onClose(@PathParam("username") String username, Session session) {
        livingSession.remove(session.getId());

        sendTextToAll(username + " live.");
    }

    private void sendTextToAll(String message) {
        livingSession.forEach((sessionId, session) -> sendText(session, message));
    }

    private void sendText(Session session, String message) {
        RemoteEndpoint.Basic basic = session.getBasicRemote();

        try {
            basic.sendText(message);
        } catch (IOException e) {
            //
        }
    }

}
